ASP.NET Core Web API Getting Started - Middleware Order
ASP.NET Core middleware must be configured in a specific order to function correctly. I previously struggled to find articles detailing this order, but I recently discovered the relevant MSDN documentation: Middleware. This article serves as a backup for my own reference to avoid losing track of this information in the future. It will be updated continuously.
Middleware Descriptions
- Developer Exception Page Middleware (UseDeveloperExceptionPage): Reports application runtime errors.
- Database Error Page Middleware (UseDatabaseErrorPage): Reports database runtime errors.
- Exception Handler Middleware (UseExceptionHandler): Catches exceptions thrown in subsequent middleware.
- HTTP Strict Transport Security (HSTS) Middleware (UseHsts): Adds the
Strict-Transport-Securityheader, which allows the site to declare itself a secure host and notifies the browser to use only HTTPS connections. - HTTPS Redirection Middleware (UseHttpsRedirection): Redirects HTTP requests to HTTPS.
TIP
Both UseHsts and UseHttpsRedirection redirect HTTP requests to HTTPS; the former is handled by the browser, while the latter is handled by the application.
Static Files Middleware (UseStaticFiles): Looks for corresponding static files in specified paths and sends them to the client upon receiving an appropriate HTTP request.
Cookie Policy Middleware (UseCookiePolicy): Ensures the application complies with GDPR regulations. For more on GDPR, please refer to Implementing GDPR in ASP.NET Core.
Routing Middleware (UseRouting): Handles routing-related processing.
Authentication Middleware (UseAuthentication): Authenticates whether a user is logged in.
Authorization Middleware (UseAuthorization): Authorizes users to access secure resources.
Session Middleware (UseSession): Handles session-related processing.
Endpoint Routing Middleware (UseEndpoints and other endpoint-related methods like MapRazorPages): Adds endpoints to the request pipeline.
Complete Middleware Order
Based on the current built-in middleware, the recommended order is as follows. In practice, you only need to use the middleware required by your project, and the order of some middleware can be adjusted:
var app = builder.Build();
if (app.Environment.IsDevelopment()) {
// UseMigrationsEndPoint and the other two are from different examples, so their specific order isn't detailed
app.UseMigrationsEndPoint();
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
} else {
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
// The most peculiar middleware; examples place it very early, yet many scenarios require it to be placed later.
// For applications using JavaScript to fetch cross-site static files, it must be placed after UseCors.
// If static files involve culture-specific content, it must be placed after UseRequestLocalization.
// To allow caching of compressed static files, it must be placed after UseResponseCompression and UseResponseCaching.
app.UseStaticFiles();
app.UseCookiePolicy();
// Unless RateLimiter only uses global filters, UseRouting should be placed before UseRateLimiter.
app.UseRouting();
app.UseRateLimiter();
// UseRequestLocalization must appear before any middleware that might check the request culture.
app.UseRequestLocalization();
// UseCors should be placed after UseRouting and before UseEndpoints.
// UseCors should be placed before UseAuthentication and UseResponseCaching.
// Currently, placing UseCors after UseResponseCaching causes this bug: https://github.com/dotnet/aspnetcore/issues/23218
app.UseCors();
// UseAuthentication should be placed before UseAuthorization.
app.UseAuthentication();
app.UseAuthorization();
// Should be placed after UseCookiePolicy and before endpoint-related middleware.
app.UseSession();
// There is no fixed order for UseResponseCompression and UseResponseCaching; if you want to cache compressed responses to reduce CPU usage, you can swap them.
app.UseResponseCompression();
app.UseResponseCaching();
// These endpoint routing middlewares starting with Map, or UseMvc/UseEndpoints, should be placed at the end.
app.MapRazorPages();
app.MapDefaultControllerRoute();
app.Run();Change Log
- 2024-04-08 Initial version created.
